package org.example.traffic.student;


import org.example.traffic.result.Result;
import org.example.traffic.student.Student;
import org.example.traffic.student.StudentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 * @author: wyk
 */
@RestController
@RequestMapping("/students")
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }


    // 新增学生信息
    @PostMapping("/add")
    public Result addStudent(@RequestBody Student student) {
        try {
            studentService.saveStudent(student);
            return Result.success();
        }catch (Exception e) {
            return Result.error("手机号重复!");
        }
    }

    // 根据ID查询学生信息
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable Integer id) {
        Student student = studentService.getStudentById(id);
        if (student!= null) {
            return new ResponseEntity<>(student, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // 查询所有学生信息
    @GetMapping
    public ResponseEntity<List<Student>> getStudents() {
        List<Student> students = studentService.getAllStudents();
        return new ResponseEntity<>(students, HttpStatus.OK);
    }

    // 根据ID删除学生信息
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudentById(@PathVariable Integer id) {
        studentService.deleteStudentById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    // 更新学生信息
    @PutMapping
    public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
        Student updatedStudent = studentService.updateStudent(student);
        return new ResponseEntity<>(updatedStudent, HttpStatus.OK);
    }

    // 按照姓名模糊查询学生
    @GetMapping("/search/name")
    public ResponseEntity<List<Student>> searchStudentsByName(@RequestParam String name) {
        List<Student> students = studentService.findStudentsByName(name);
        return new ResponseEntity<>(students, HttpStatus.OK);
    }

    // 按照组织ID查询该组织下的所有学生
    @GetMapping("/search/organization")
    public ResponseEntity<List<Student>> searchStudentsByOrganizationId(@RequestParam Integer organizationId) {
        List<Student> students = studentService.findStudentsByOrganizationId(organizationId);
        return new ResponseEntity<>(students, HttpStatus.OK);
    }
}
